# -*- coding: utf-8 -*-

import re

from flask import Flask, request, render_template, g
from django.conf import settings
from google.appengine.api.namespace_manager import get_namespace, set_namespace

from .blueprints.lenta import code as lenta
from .blueprints.lenta.code.views.lenta import _fetch_lenta
from .blueprints.auth import code as auth

from .blueprints.user import code as user
from .blueprints.user.code.backends.working.models import User as user_class
from .blueprints.user.code.backends.working.exception import UserNameDuplicateError, OneUserPerOpenidError

from . import views as application_views


app = Flask(__name__)
app.config.update(
    SECRET_KEY = settings.FLASK_SETTINGS.SECRET_KEY
)

#########################
# configure application #
#########################

app.before_request(auth.set_user)
app.before_request(lambda: set_namespace(g.user.name) if g.user else set_namespace(""))

app.register_error_handler(
    OneUserPerOpenidError,
    lambda e: render_template('app_error.html', errmsg="Only one user per OpenID is allowed")
)

@app.context_processor
def inject_into_template():
    """ """
    view_args = request.view_args
    
    g.namespace = get_namespace()
    
    ctx = {
        'c': {
            'view_args': view_args ,
            'create_login_url': auth.create_login_url,
            'create_logout_url': auth.users.create_logout_url,
            'debug_clientside': settings.DEBUG_CLIENTSIDE
        }
    }
    
    if 'lenta_id' in view_args:
        lenta = _fetch_lenta(view_args['lenta_id'], view_args.get('namespace') or get_namespace())
        ctx['c'].update({'lenta': lenta})
        
    return ctx
    
#######################
# register blueprints #
#######################    

REGEXP = re.compile("^\w{3,10}$")
is_username_valid = lambda name: REGEXP.match(name)

user.register(app, '/user',
    {
        'user_name_validator': lambda name: True if is_username_valid(name) else False
    }
)

auth.register(app, '/auth',
    {
        'user_class': user_class,
        'user_exceptions': {UserNameDuplicateError: "name is occupied"},
        'default_destination': '/',
        'session_key_name': 'user_data',
        'user_name_validator': lambda name: (name, None) if is_username_valid(name) else (None, 'name is invalid')
    }
)

lenta.register(app, '/lenta',
    {
        'db_backend': {},
        'login_required': auth.login_required
    }
)

#####################################
# register application url handlers #
#####################################

app.add_url_rule('/', 'root', application_views.root_handler)